package com.ourcraft.informationcollectionsystem.service.province.dataFormExamine;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ourcraft.informationcollectionsystem.entity.*;
import com.ourcraft.informationcollectionsystem.mapper.*;
import com.ourcraft.informationcollectionsystem.service.common.addQueryHistory.AddHistoryService;
import com.ourcraft.informationcollectionsystem.utils.statusCode.DataReportFormStatus;
import com.ourcraft.informationcollectionsystem.utils.statusCode.HistoryType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * DataFormExamineServiceImpl provide DataReportForm-Examine-related services interface implementation.
 *
 * @author Liu Yiming
 * @since 2023-11-04
 */
@Service
public class DataFormExamineServiceImpl implements DataFormExamineService{
    @Autowired
    private DataReportFormMapper dataReportFormMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private AddHistoryService addHistoryService;

    /**
     * Get the user's role ID from database recording to user ID.
     *
     * @param userId The ID of the user.
     * @return role ID of the user.
     */
    private int getRoleId(int userId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        User user = userMapper.selectOne(queryWrapper);
        return user.getRoleId();
    }

    /**
     * Get the user's city name from database recording to user ID.
     *
     * @param userId The ID of the user.
     * @return city name of the user.
     */
    private String getCityName(int userId) {
        QueryWrapper<City> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        City city = cityMapper.selectOne(queryWrapper);
        return city.getCityName();
    }

    /**
     * Retrieves information of list of all forms recording to user ID
     *
     * @param userId The ID of the user.
     * @return information of list of all forms.
     */
    @Override
    public ArrayList<Map<String, Object>> getAllRecords(int userId) {
        ArrayList<Map<String, Object>> data0 = new ArrayList<>();
        String cityName = "";
        // 如果用户为市用户则设置cityname为用户所在市的名称
        if (getRoleId(userId) == 2) {
            cityName = getCityName(userId);
        }
        // 筛选表单
        List<DataReportFormDetail> dataReportFormDetails = dataReportFormMapper.selectDataReportFormDetails();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (DataReportFormDetail item: dataReportFormDetails) {
            // 筛选条件为：省用户获取所有数据报表，市用户获取所在市内的所有数据报表
            if (Objects.equals(cityName, "") || Objects.equals(cityName, item.getCompanyCity())) {
                Map<String, Object> map = new HashMap<>();
                // 添加键值对
                map.put("formID", item.getFormId());
                map.put("formCompanyName", item.getCompanyChineseName());
                map.put("formCompanyCity", item.getCompanyCity());
                map.put("formInvestigationName", item.getInvestigationTitle());
                map.put("formStartTotalNum", item.getFormStartTotalNum());
                map.put("formEndTotalNum", item.getFormEndTotalNum());
                map.put("formDecreaseType", item.getFormDecreaseType());
                map.put("formFirstReason", item.getFormFirstReason());
                map.put("formSecondReason", item.getFormSecondReason());
                map.put("formThirdReason", item.getFormThirdReason());
                map.put("formReasonDescription", item.getFormReasonDescription());
                map.put("formExamineStatus", item.getFormExamineStatus());
                // 格式化最后提交日期
                Date date = item.getLastSubmitDate();
                String date_str;
                if (date == null) {
                    date_str = "";
                } else {
                    date_str = dateFormat.format(date);
                }
                map.put("formSubmitTime", date_str);
                data0.add(map);
            }
        }
        return data0;
    }

    /**
     * pass the form in request.
     *
     * @param formId The ID of the form to be passed.
     * @return Operation result.
     */
    @Override
    public boolean passForm(int formId) {
        // 获取数据报表当前的审核状态
        QueryWrapper<DataReportForm> wrapper = new QueryWrapper<>();
        wrapper.eq("form_id", formId);
        DataReportForm dataReportForm = dataReportFormMapper.selectOne(wrapper);
        int formExamineStatues = dataReportForm.getFormExamineStatus();
        // 添加审核通过的历史记录
        addHistoryService.addFormSubmission(
                formId,
                -1,
                HistoryType.exePass(DataReportFormStatus.build(formExamineStatues)).ordinal(),
                "",
                false
        );
        // 更新该数据报表的审核状态为对应的通过状态
        DataReportForm newDataReportForm = new DataReportForm();
        if (formExamineStatues == DataReportFormStatus.WAIT_CITY.ordinal()) {
            newDataReportForm.setFormExamineStatus(DataReportFormStatus.WAIT_PROVINCE.ordinal());
        } else if (formExamineStatues == DataReportFormStatus.WAIT_PROVINCE.ordinal()) {
            newDataReportForm.setFormExamineStatus(DataReportFormStatus.PASS.ordinal());
            // 查找该企业的下一个数据报表，将其formStartTotalNum设置为当前通过报表的formEndTotalNum
            int formEndTotalNum = dataReportForm.getFormEndTotalNum();

            int companyId = dataReportForm.getCompanyId();
            QueryWrapper<DataReportForm> newWrapper = new QueryWrapper<>();
            newWrapper.eq("company_id", companyId);
            newWrapper.gt("form_id", formId);
            newWrapper.orderByAsc("form_id");

            List<DataReportForm> list = dataReportFormMapper.selectList(newWrapper);
            if (!list.isEmpty()) {
                int nextFormId = list.get(0).getFormId();
                DataReportForm nextDataReportForm = new DataReportForm();
                nextDataReportForm.setFormStartTotalNum(formEndTotalNum);
                nextDataReportForm.setFormExamineStatus(DataReportFormStatus.NOT_FILL.ordinal());
                QueryWrapper<DataReportForm> nextWrapper = new QueryWrapper<>();
                nextWrapper.eq("form_id", nextFormId);
                dataReportFormMapper.update(nextDataReportForm, nextWrapper);
            }
        } else {
            return false;
        }
        return dataReportFormMapper.update(newDataReportForm, wrapper) != 0;
    }

    /**
     * return back the form in request.
     *
     * @param formId The ID of the form to be returned back.
     * @param reason The return back operation reason.
     * @param reasonDescription The detail description of the reason “其他”.
     * @return Operation result.
     */
    @Override
    public boolean returnBackForm(int formId, String reason, String reasonDescription) {
        // 获取数据报表当前的审核状态
        QueryWrapper<DataReportForm> wrapper = new QueryWrapper<>();
        wrapper.eq("form_id", formId);
        DataReportForm dataReportForm = dataReportFormMapper.selectOne(wrapper);
        int formExamineStatues = dataReportForm.getFormExamineStatus();
        // 添加审核退回的历史记录
        addHistoryService.addFormSubmission(
                formId,
                -1,
                HistoryType.exeReturn(DataReportFormStatus.build(formExamineStatues)).ordinal(),
                !Objects.equals(reason, "其他") ? reason : reasonDescription,
                false
        );
        // 更新该数据报表的审核状态为对应的退回状态
        DataReportForm newDataReportForm = new DataReportForm();
        if (formExamineStatues == DataReportFormStatus.WAIT_CITY.ordinal()) {
            newDataReportForm.setFormExamineStatus(DataReportFormStatus.RETURNED_BY_CITY.ordinal());
        } else if (formExamineStatues == DataReportFormStatus.WAIT_PROVINCE.ordinal()) {
            newDataReportForm.setFormExamineStatus(DataReportFormStatus.RETURNED_BY_PROVINCE.ordinal());
        } else {
            return false;
        }
        return dataReportFormMapper.update(newDataReportForm, wrapper) != 0;
    }
}
